import { Ref } from 'vue';
import type { Cell, Column } from '../types';

type ClearSelectionFn = (selectedCells: Set<string>) => void;
type GetCellIdFn = (row: number, col: number) => string;
type SaveStateFn = () => void;
type AddRowFn = (position?: number) => void;
type AddColumnFn = (position?: number) => void;

export function useDragHandlers(
  props: any,
  tableData: Ref<Cell[][]>,
  columns: Ref<Column[]>,
  selectedCells: Ref<Set<string>>,
  dragOverCell: Ref<{ row: number; col: number } | null>,
  clearSelection: ClearSelectionFn,
  getCellId: GetCellIdFn,
  saveState: SaveStateFn,
  addRow: AddRowFn,
  addColumn: AddColumnFn
) {
  /**
   * 确保列存在，如果不存在则创建新列
   * @param colIndex 列索引
   */
  const ensureColumnExists = (colIndex: number) => {
    const getColumnLetter = (index: number): string => {
      let letter = '';
      while (index >= 0) {
        letter = String.fromCharCode(65 + (index % 26)) + letter;
        index = Math.floor(index / 26) - 1;
      }
      return letter;
    };

    while (columns.value.length <= colIndex) {
      const newColumnIndex = columns.value.length;
      columns.value.push({ name: getColumnLetter(newColumnIndex) });

      // 为所有行添加新列
      for (const row of tableData.value) {
        row.push({
          name: '',
          id: '',
          type: '',
          brandId: '',
          customerId: ''
        });
      }
    }
  };

  /**
   * 确保行存在，如果不存在则创建新行
   * @param rowIndex 行索引
   */
  const ensureRowExists = (rowIndex: number) => {
    while (tableData.value.length <= rowIndex) {
      const newRow: Cell[] = [];
      for (let j = 0; j < columns.value.length; j++) {
        newRow.push({
          name: '',
          id: '',
          type: '',
          brandId: '',
          customerId: ''
        });
      }
      tableData.value.push(newRow);
    }
  };

  /**
   * 处理拖拽进入事件
   * @param event 拖拽事件
   * @param rowIndex 行索引
   * @param colIndex 列索引
   */
  const handleDragEnter = (event: DragEvent, rowIndex: number, colIndex: number) => {
    if (!props.dragging) return;

    event.preventDefault();
    event.stopPropagation();
    // 清空之前的选中
    clearSelection(selectedCells.value);
    // 设置当前单元格为选中状态
    const cellId = getCellId(rowIndex, colIndex);
    selectedCells.value.add(cellId);
    dragOverCell.value = { row: rowIndex, col: colIndex };
  };

  /**
   * 处理拖拽离开事件
   * @param event 拖拽事件
   */
  const handleDragLeave = (event: DragEvent) => {
    if (!props.dragging) return;
    event.preventDefault();
    dragOverCell.value = null;
  };

  /**
   * 处理拖拽放置事件
   * @param event 拖拽事件
   * @param rowIndex 行索引
   * @param colIndex 列索引
   */
  const handleDrop = (event: DragEvent, rowIndex: number, colIndex: number) => {
    if (!props.dragging) return;

    event.preventDefault();
    event.stopPropagation();

    dragOverCell.value = null;

    try {
      // 处理拖拽数据的逻辑保持不变
      const dataStr = event.dataTransfer?.getData('application/json');
      if (dataStr) {
        const group = JSON.parse(dataStr);
        // 处理拖拽数据
        if (group.type === 'table-cell' && Array.isArray(group.data)) {
          // 确保有足够的列来容纳数据
          const requiredColumns = colIndex + group.data.length;
          while (columns.value.length < requiredColumns) {
            ensureColumnExists(columns.value.length);
          }
          // 填充数据
          group.data.forEach((value: Cell, index: number) => {
            const targetCol = colIndex + index;
            if (tableData.value[rowIndex]) {
              // 合并对象以保持类型正确性
              tableData.value[rowIndex][targetCol] = {
                ...tableData.value[rowIndex][targetCol],
                ...value
              };
            }
          });
          saveState();
        }
        // 处理外部数据
        else if (group.type === 'external-data') {
          // 确保目标单元格存在
          ensureColumnExists(colIndex);

          // 确保有足够的行
          ensureRowExists(rowIndex);

          // 将外部数据设置为 name 字段
          tableData.value[rowIndex][colIndex].name = group.data.join(', ');
          saveState();
        }
      } else {
        const textData = event.dataTransfer?.getData('text/plain');
        if (textData) {
          // 确保目标单元格存在
          ensureColumnExists(colIndex);

          // 确保有足够的行
          ensureRowExists(rowIndex);

          // 将文本数据设置为 name 字段
          tableData.value[rowIndex][colIndex].name = textData;
          saveState();
        }
      }
      clearSelection(selectedCells.value);
    } catch (error) {
      console.error('Drop error:', error);
    }
  };

  return {
    handleDragEnter,
    handleDragLeave,
    handleDrop
  };
}
